package ar.edu.unsam.algo3.plantasvszombies.wicket

import ar.edu.unsam.algo3.plantasvszombies.dominio.Fila
import ar.edu.unsam.algo3.plantasvszombies.ui.ApplicationModels.BatallaAppModel
import java.util.ArrayList
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.markup.html.panel.FeedbackPanel
import org.apache.wicket.markup.html.panel.Panel
import org.apache.wicket.model.CompoundPropertyModel
import org.apache.wicket.model.PropertyModel
import org.uqbar.wicket.xtend.WicketExtensionFactoryMethods
import org.uqbar.wicket.xtend.XAjaxLink
import org.uqbar.wicket.xtend.XListView
import org.uqbar.commons.model.UserException

class BatallaPanel extends Panel {
	extension WicketExtensionFactoryMethods = new WicketExtensionFactoryMethods
	var BatallaAppModel batallaApp
	var feedbackPanel = new FeedbackPanel("feedbackPanel")

	new(String id, Fila fila) {
		super(id)
		batallaApp = new BatallaAppModel
		batallaApp.fila = fila
		batallaApp.batalla.fila = fila

		val Form<BatallaAppModel> formBatalla = new Form<BatallaAppModel>("formBatalla",
			new CompoundPropertyModel<BatallaAppModel>(batallaApp))
		formBatalla.outputMarkupId = true

		agregarDatos(formBatalla)
		agregarTabla(formBatalla)
		agregarAcciones(formBatalla)

		addChild(formBatalla)
		batallaApp.mostrar
	}

	def agregarDatos(Form<BatallaAppModel> form) {
		form.addChild(new Label("recursos", new PropertyModel(batallaApp.fila.jardin, "recursos")))
		feedbackPanel.outputMarkupId = true
		form.addChild(feedbackPanel)
	}

	def agregarTabla(Form<BatallaAppModel> form) {
		val listView = new XListView("resultado")
		listView.populateItem = [ item |
			item.model = item.modelObject.asCompoundModel
			item.addChild(new Label("fila", item.modelObject))
		]
		form.addChild(listView)
	}

	def agregarAcciones(Form<BatallaAppModel> form) {
		val listView = new XListView("result")
		listView.populateItem = [ item |
			item.model = item.modelObject.asCompoundModel
			val miBoton = new XAjaxLink<Object>("seleccionar") => [
				onClick = [ target |
					try{
					batallaApp.batalla.resultado = new ArrayList<String>
					batallaApp.selectedItem = item.modelObject
					form.modelObject.atacar
					target.add(form)
					}catch(UserException e){
						error(e.message)
						target.add(feedbackPanel)
					}
				]
				
			]
			miBoton.addChild(new Label("nombre"))
			miBoton.addChild(new Label("defensa"))
			miBoton.addChild(new Label("ataque"))
			item.addChild(miBoton)
		]
		form.addChild(
			new XAjaxLink("salir") => [
				onClick = [ target |
					target.add(this.parent)
				]
			])
		form.addChild(listView)
	}

}
